import asyncio
import threading


task = None
event_loop = None


async def async_task(id):
    count = 0
    while True:
        print(f"{id} 协程正在运行 {count}")
        await asyncio.sleep(1)
        count += 1


async def main_test():
    global task
    global event_loop
    task = asyncio.gather(async_task("lilisi"))
    event_loop = asyncio.get_running_loop()
    try:
        await task
    except asyncio.CancelledError:
        print("协程被取消")
        task = None
    except Exception as e:
        print(f"发生异常{e}")


def main():
    asyncio.run(main_test())
    print("主协程结束")


def input_cmd():
    help_str = """
1.运行协程
2.取消协程
3.添加 本地 协程对象
#4.取消 本地 协程对象
q.退出
"""
    global task
    local_task = None
    while True:
        cmd = input(help_str)
        if cmd == "1":
            if task == None:
                t1 = threading.Thread(target=main)
                t1.daemon = True
                t1.start()
            else:
                print("协程正在运行")
        elif cmd == "2":
            task.cancel()
        elif cmd == "3":
            local_task = async_task("Jack", 5)
            event_loop.create_task(local_task)
            print("添加协程任务成功")
        # elif cmd == "4":      -->协程函数, 非协程任务Task() 无法取消
        #     if local_task != None:
        #         local_task.cancel()
        #         print("取消协程任务成功")
        #     else:
        #         print("没有协程任务")
        elif cmd == "q":
            break
        else:
            print("输入错误")


if __name__ == "__main__":
    t1 = threading.Thread(target=main)
    t1.daemon = True
    t1.start()
    input_cmd()
